﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using YLServiceCLient.YLAdminClient;
using YLPublicService.TransferModel;
using YLServerInterface.UserControls;
using YLServerInterface.ServerConfig;
using GifTools;
using YLServerInterface.FunctionalClass;
using YLServerInterface.FTP;

namespace YLServerInterface.Forms
{
    /// <summary>
    /// Interaction logic for frmWorkItemProcess.xaml
    /// </summary>
    public partial class frmWorkItemProcess : Window
    {
        frmWorkItemProcess()
        {
            InitializeComponent();
        }

        AdminServiceClient client = AdminServiceClient.GetServiceClient();
        Process processConfig;
        WorkItem2ServerUser workItem;
        TemplateItem.TemplateDetial templateDetial;
        public frmWorkItemProcess(WorkItem2ServerUser workitem)
            : this()
        {
            processConfig = client.GetTemplateProcessConfig(client.loginSuccessGuid, workitem.TemplateID);
            templateDetial = TemplateItem.TemplateDetial.FromXML(workitem.Detial);
            lstParamters.DataContext = templateDetial.mRequireValues.mItem.ToArray();
            workItem = workitem;
            DataContext = workitem;
            //准备环境
            downLoadFiles();
            initImageCutter();
        }
        /// <summary>
        /// 下载的图片保存位置
        /// </summary>
        string workItemDir;
        ServerConfig.YLServerConfig config = YLServerConfig.GetConfig();
        void downLoadFiles()
        {
            //创建保存目录
            workItemDir =
                Common.makeDir(
                    Common.conbindPath(config.WorkItemsFolder, workItem.FilesRelativeFolder))
                    .FullName;
            txtbLocalSaveDir.Text = workItemDir;
            YLServerInterface.FTP.ClientAdapter ftpclient = new FTP.ClientAdapter(false);
            //下载图片失败时提示：
            ftpclient.OnTransferError += msg =>
                MessageBox.Show(msg);
            //下载用户上传的文件
            ftpclient.DownloadFiles(workItem.FilesRelativeFolder, workItemDir);
            //下载制作模板需要的文件
            ftpclient.DownloadFiles(workItem.TemplateAttachmentsFolder, workItemDir);
        }
        void initImageCutter()
        {
            var serverConfig = ServerConfig.YLServerConfig.GetConfig();
            //下载保存时候的规则
            var mix =
                    from config in processConfig.mImages.mImage
                    where config.mIsDraw.ToLower() == "false"//上传图片信息
                    from att in templateDetial.mRequireAttchments.mItem//所有图片处理逻辑
                    where config.mName.ToLower() == att.mName.ToLower()
                    select new
                    {
                        imgPath = Common.conbindPath(workItemDir, att.mValue),//上传时的文件名  在上传对象中
                        savePath = Common.conbindPath(workItemDir, config.mSaveName),//保存时使用的文件名，在处理逻辑对象中
                        width = config.mWidth,
                        height = config.mHeigth
                    };
            ////上传图片信息
            //templateDetial.mRequireAttchments.mItem[0].
            ////所有图片处理逻辑
            //processConfig.mImages.mImage
            foreach (var info in mix)
            {
                ImageCutter cutter = new ImageCutter(info.imgPath, info.savePath,
                    Convert.ToDouble(info.width),
                    Convert.ToDouble(info.height));
                cutter.Width = Convert.ToDouble(config.ImageCutterControlWidth);
                cutter.Height = Convert.ToDouble(config.ImageCutterControlHeight);
                wPnlCutterContainer.Children.Add(cutter);
                cutters.Add(cutter);
            }
        }
        List<ImageCutter> cutters = new List<ImageCutter>();

        private void btnMakeValuegif_Click(object sender, RoutedEventArgs e)
        {
            GifMaker gifmaker = new GifMaker(processConfig, config.TTFPath);
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var item in templateDetial.mRequireValues.mItem)
            {
                dict[item.mName] = item.mValue;
            }
            gifmaker.MakeImages(dict, workItemDir);
        }

        private void btnMakePhotoAndExe_Click(object sender, RoutedEventArgs e)
        {
            foreach (var cutter in cutters)
            {
                cutter.Cut();
            }
            FlashExeMaker maker = new FlashExeMaker();
            var ret = maker.MakeExe(Common.conbindPath(workItemDir, config.YaZhiProjectFileName));
            if (ret.Item1)
            {
                MessageBox.Show("生成成功");
            }
            else
            {
                MessageBox.Show("生成失败\n" + ret.Item2);
            }
        }

        private void btnUploadWorkItem_Click(object sender, RoutedEventArgs e)
        {
            //修改数据库
            var isSucces = client.UpdateWorkItem(workItem.WorkItemID, WorkItemStatus.ProcessFinish);
            if (isSucces)
            {//上传文件只服务器
                ClientAdapter ftpclient = new ClientAdapter(false);
                var remoteDir = workItem.FilesRelativeFolder;
                var localFilePath = Common.conbindPath(workItemDir, workItem.TemplateName) + ".exe";
                var uploadRet = ftpclient.UploadFile(remoteDir, localFilePath);
                MessageBox.Show("EXE是否成功？：" + uploadRet.ToString());
            }
            else
                MessageBox.Show("更改工作项状态至已完成失败，重试");
        }
    }
}
